//
// Created by martin on 2/5/22.
//

#ifndef MUDUO_CONDITION_H
#define MUDUO_CONDITION_H

#include "muduo/base/Mutex.h"

#include <pthread.h>

namespace muduo
{

class Condition
{
public:
    explicit Condition(MutexLock& mutex)
    : mutex_(mutex)
    {
        MCHECK(pthread_cond_init(&cond_, NULL));
    }

    ~Condition()
    {
        MCHECK(pthread_cond_destroy(&cond_));
    }

    void wait()
    {
        MutexLock::UnassignGuard ug(mutex_);
        MCHECK(pthread_cond_wait(&cond_, mutex_.getPthreadMutex()));
    }

    // return true if time out, false otherwise.
    bool waitForSeconds(double seconds);

    // notify one thread waiting on cond_
    void notify()
    {
        MCHECK(pthread_cond_signal(&cond_));
    }

    // notify all threads waiting on cond_
    void notifyAll()
    {
        MCHECK(pthread_cond_broadcast(&cond_));
    }

private:
    MutexLock& mutex_;
    pthread_cond_t cond_;
};

} // namespace muduo




#endif //MUDUO_CONDITION_H
